package com.inhim.pjhim.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.inhim.pjhim.R;
import com.inhim.pjhim.app.BaseActivity;
import com.inhim.pjhim.app.MyApplication;
import com.inhim.pjhim.entity.LoginEntity;
import com.inhim.pjhim.http.MyOkHttpClient;
import com.inhim.pjhim.http.Urls;
import com.inhim.pjhim.utils.PrefUtils;
import com.inhim.pjhim.view.BToast;
import com.inhim.pjhim.view.CenterDialog;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import java.io.IOException;
import java.util.HashMap;

import okhttp3.Request;

public class LoginActivity extends BaseActivity implements View.OnClickListener {
    private EditText ed_mobile, ed_password;
    private TextView tv_forget_password;
    private ImageView iv_weixin, iv_back;
    private Button btn_login;
    private Gson gson;
    private CenterDialog centerDialog;
    private CheckBox rb_close_eyes;
    private LinearLayout lin_regist;
    /**
     * 微信登录相关
     */
    private IWXAPI api;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public Object offerLayout() {
        return R.layout.activity_login_new;
    }

    @Override
    public void onBindView() {
        MyApplication.instance.addActivity(this);
        gson = new Gson();
        if (PrefUtils.getBoolean("isLogin", false)) {
            Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
            startActivity(intent);
            finish();
        }
        initView();
    }

    @Override
    public void destory() {

    }

    private void initView() {
        //imageview=findViewById(R.id.imageview);
        //imageview.setImageResource(R.mipmap.about);
        //GlideUtils.displayFromId(R.mipmap.ic_launcher,imageview,this);
        lin_regist=findViewById(R.id.lin_regist);
        lin_regist.setOnClickListener(v -> {
            Intent intent=new Intent(LoginActivity.this,RegisterActivity.class);
            startActivity(intent);
        });
        rb_close_eyes=findViewById(R.id.rb_close_eyes);
        rb_close_eyes.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if(isChecked){
                ed_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
            }else{
                ed_password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            }
        });
        ed_mobile = findViewById(R.id.ed_mobile);
     /*   ed_mobile.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(s.toString().length()>=11){
                    btn_gecode.setEnabled(true);
                    //btn_gecode.setBackgroundResource(R.drawable.backgroud_button_getcode2);
                    btn_gecode.setTextColor(Color.parseColor("#0079D7"));
                }else{
                    btn_gecode.setEnabled(false);
                    //btn_gecode.setBackgroundResource(R.drawable.backgroud_button_getcode1);
                    btn_gecode.setTextAppearance(R.style.btn_getcode);
                    btn_gecode.setTextColor(Color.parseColor("#999999"));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });*/
        ed_password = findViewById(R.id.ed_password);
        ed_password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(s.toString().length()>=6){
                    btn_login.setEnabled(true);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        //tv_encounter_problem = findViewById(R.id.tv_encounter_problem);
        iv_weixin = findViewById(R.id.iv_weixin);
        btn_login = findViewById(R.id.btn_login);
        //tv_encounter_problem.setOnClickListener(this);
        iv_weixin.setOnClickListener(this);
        btn_login.setOnClickListener(this);
        btn_login.setEnabled(false);
        /*btn_gecode = findViewById(R.id.btn_gecode);
        btn_gecode.setOnClickListener(this);
        btn_gecode.setEnabled(false);*/
        //tv_agreement = findViewById(R.id.tv_agreement);
        //tv_agreement.setOnClickListener(this);
        /*cb_save_pw = findViewById(R.id.cb_save_pw);
        cb_save_pw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isOk = isChecked;
            }
        });*/
        iv_back = findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);
        /*tv_quick_login=findViewById(R.id.tv_quick_login);
        tv_user_password=findViewById(R.id.tv_user_password);
        tv_quick_login.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if(isChecked){
                btn_gecode.setVisibility(View.VISIBLE);
                ed_code.setVisibility(View.GONE);
                ed_password.setVisibility(View.VISIBLE);
            }
        });
        tv_user_password.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if(isChecked){
                btn_login.setEnabled(true);
                btn_gecode.setVisibility(View.GONE);
                ed_code.setVisibility(View.VISIBLE);
                ed_password.setVisibility(View.GONE);
            }
        });
*/
        tv_forget_password=findViewById(R.id.tv_forget_password);
        tv_forget_password.setOnClickListener(v -> {
            Intent intent=new Intent(LoginActivity.this,ForgetPasswordActivity.class);
            startActivity(intent);
        });
    }

    private void loGin() {
        HashMap map = new HashMap();
        /*if (!isOk) {
            BToast.showText("请阅读并同意用户协议 ", Toast.LENGTH_LONG, false);
            return;
        }*/
        if (ed_mobile.getText().toString().equals("")) {
            BToast.showText("请输入手机号码 ", Toast.LENGTH_LONG, false);
            return;
        }
        /*if(tv_quick_login.isChecked()){
            if (ed_password.getText().toString().equals("")) {
                BToast.showText("请输入验证码 ", Toast.LENGTH_LONG, false);
                return;
            }
        }else{
            if (ed_code.getText().toString().equals("")) {
                BToast.showText("请输入密码 ", Toast.LENGTH_LONG, false);
                return;
            }
        }*/
        if (ed_password.getText().toString().equals("")) {
            BToast.showText("请输入密码 ", Toast.LENGTH_LONG, false);
            return;
        }
       /*map.put("mobile", ed_mobile.getText().toString());
        map.put("openId", "");
        map.put("password", ed_password.getText().toString());
        map.put("validate", "");*/
        String examUrl = Urls.onPwLogin(ed_mobile.getText().toString(),ed_password.getText().toString());
        MyOkHttpClient.getInstance().asyncJsonPostNoToken(examUrl, map, new MyOkHttpClient.HttpCallBack() {
            @Override
            public void onError(Request request, IOException e) {
            }

            @Override
            public void onSuccess(Request request, String results) {
                LoginEntity loginEntity = gson.fromJson(results, LoginEntity.class);
                if (loginEntity.getCode() == 0) {
                    PrefUtils.putLong("expire", loginEntity.getExpire());
                    PrefUtils.putString("token", loginEntity.getToken());
                    PrefUtils.putBoolean("isLogin", true);
                    Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
                    startActivity(intent);
                    finish();
                } else if (loginEntity.getCode() == 500) {
                    /*if(tv_quick_login.isChecked()){
                        Intent intent = new Intent(LoginActivity.this, BindPhoneActivity.class);
                        startActivity(intent);
                    }else{
                        BToast.showText(loginEntity.getMsg(), Toast.LENGTH_LONG, false);
                    }*/
                    BToast.showText(loginEntity.getMsg(), Toast.LENGTH_LONG, false);
                } else {
                    BToast.showText(loginEntity.getMsg(), Toast.LENGTH_LONG, false);
                }
            }
        });
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_encounter_problem:
                setCenterDiaolog();
                break;
            case R.id.iv_weixin:
                /*if (!isOk) {
                    BToast.showText("请阅读并同意用户协议 ", Toast.LENGTH_LONG, false);
                    return;
                }*/
                //通过WXAPIFactory工厂获取IWXApI的示例
                api = WXAPIFactory.createWXAPI(this, MyApplication.appID, true);
                //将应用的appid注册到微信
                api.registerApp(MyApplication.appID);
                SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";
//                req.scope = "snsapi_login";//提示 scope参数错误，或者没有scope权限
                req.state = "wechat_sdk_微信登录";
                api.sendReq(req);
                break;
            case R.id.btn_login:
                loGin();
                break;
            /*case R.id.btn_gecode:
                sendSMS();
                break;*/
            case R.id.tv_agreement:
                Intent intent = new Intent(LoginActivity.this, WebViewActivity.class);
                intent.putExtra("Type", "agreement");
                startActivity(intent);
                break;
            case R.id.iv_back:
                finish();
                break;
            default:
                break;
        }
    }

    private void setCenterDiaolog() {
        View outerView = LayoutInflater.from(LoginActivity.this).inflate(R.layout.dialog_about, null);
        Button btn_ok = outerView.findViewById(R.id.btn_ok);
        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                centerDialog.dismiss();
            }
        });
        //防止弹出两个窗口
        if (centerDialog != null && centerDialog.isShowing()) {
            return;
        }

        centerDialog = new CenterDialog(LoginActivity.this, R.style.ActionSheetDialogBotoomStyle);
        //将布局设置给Dialog
        centerDialog.setContentView(outerView);
        centerDialog.show();//显示对话框
    }
}
